<?php
namespace app\farm\model;

use app\BaseModel;
use app\farm\model\BalanceWater;
use app\farm\model\User;
use app\publics\model\TmplConfig;
use app\shop\model\DistributionCash;
use app\shop\model\IntegralLog;
use longbingcore\wxcore\PayModel;
use longbingcore\wxcore\PushMsgModel;
use think\facade\Db;

class ClaimOrder extends BaseModel
{
    //定义表名
    protected $name = 'lbfarm_claim_order';


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);;

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-14 15:45
     * @功能说明:添加关联
     */
    public function updateSome($id,$data){

        $server = new \app\farm\server\Claim();

        $claim_text_model = new ClaimText();

        $source_text_model= new LandSourceText();

        $monitor_text_model= new MonitorText();

        $server->addObserver($claim_text_model);

        $server->addObserver($source_text_model);

        $server->addObserver($monitor_text_model);

        $server->notify($id,$data);

        return true;

    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page=10){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-12-16 15:39
     * @功能说明:回调
     */
    public function orderResult($order_code,$transaction_id){

        $order = $this->dataInfo(['order_code'=>$order_code]);

        if(!empty($order)&&$order['pay_type']==1){

            $update = [

                'pay_time' => time(),

                'pay_type' => 2,

                'transaction_id' => $transaction_id
            ];

            Db::startTrans();

            $this->dataUpdate(['id'=>$order['id']],$update);
            //扣除余额
            if($order['balance']>0){

                $water_model = new BalanceWater();

                $res = $water_model->addWater($order,2,0);

                if($res==0){

                    Db::rollback();

                }
            }
            //添加流水
            $water_model = new FinanceWater();

            $water_model->addWater($order['id'],1,1,1);

            $integral_model = new IntegralLog();
            //增加佣金
            $integral_model->integralUserAdd($order['user_id'],$order['get_integral'],$order['uniacid'],2,5,$order['id'],0,$order);
            //分销
            $cash_model = new DistributionCash();
            //增加分销激励
            $cash_model->addUserCash($order,3);
            //分销到账
            $cash_model->cashArrival($order,3);

            $collage_model = new CollageStart();
            //拼团
            $collage_model->atvResult($order['id']);

            Db::commit();

            $sys_model = new PushMsgModel($order['uniacid']);

            $sys_model->sendMsg($order,8);

            $sys_model->sendMsg($order,10);

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:超时自动退款
     */
    public function autoCancelOrder($uniacid,$user_id=0){

        $dis[] = ['uniacid','=',$uniacid];

        $dis[] = ['pay_type','=',1];

        $dis[] = ['over_time','<',time()];

        if(!empty($user_id)){

            $dis[] = ['user_id','=',$user_id];
        }

        $order = $this->where($dis)->select()->toArray();

        if(!empty($order)){

            foreach ($order as $value){

                $this->cancelOrder($value);

            }

        }

        return true;
    }



    /**
     * @author chenniang
     * @DataTime: 2021-04-01 10:13
     * @功能说明:退款
     */
    public function cancelOrder($order,$refund =1,$payConfig=[]){

        Db::startTrans();

        if($refund==2){

            $res = $this->refundCash($payConfig,$order);

            if($res!=true){

                Db::rollback();

                return ['code'=>500,'msg'=>'退款失败'];
            }

        }else{
            //取消订单
            $collage_model = new CollageStart();

            $collage_model->cancelOrderAtvFail($order['id']);

        }

        $res = $this->dataUpdate(['id'=>$order['id'],'pay_type'=>$refund],['pay_type'=>-1,'cancel_time'=>time()]);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'取消失败'];
        }

        $claim_model = new Claim();

        $claim = $claim_model->dataInfo(['id'=>$order['goods_id']]);
        //加销量减库存
        $update = [

            'stock'    => $claim['stock'] +$order['num'],

            'sale_num' => $claim['sale_num']-$order['num'],

            'lock'     => $claim['lock']+1

        ];

        $res = $claim_model->dataUpdate(['id'=>$claim['id'],'lock'=>$claim['lock']],$update);

        if($res==0){

            Db::rollback();

            return ['code'=>500,'msg'=>'取消失败'];

        }

        Db::commit();

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-18 13:53
     * @功能说明:退钱
     */
    public function refundCash($payConfig,$pay_order){

        if($pay_order['pay_price']<=0){

            return true;
        }

        $water_model = new FinanceWater();

        $water_model->addWater($pay_order['id'],2,1,1);

        if($pay_order['pay_model']==1){
            //微信退款
            $response = orderRefundApi($payConfig,$pay_order['pay_price'],$pay_order['pay_price'],$pay_order['transaction_id']);
            //如果退款成功修改一下状态
            if ( isset( $response[ 'return_code' ] ) && isset( $response[ 'result_code' ] ) && $response[ 'return_code' ] == 'SUCCESS' && $response[ 'result_code' ] == 'SUCCESS' ) {

                $response['out_refund_no'] = !empty($response['out_refund_no'])?$response['out_refund_no']:$pay_order['order_code'];

                $this->dataUpdate(['id'=>$pay_order['id']],['out_refund_no'=>$response['out_refund_no']]);

            }else {
                //失败就报错
                $discption = !empty($response['err_code_des'])?$response['err_code_des']:$response['return_msg'];

                return ['code'=>500,'msg'=> $discption];

            }

        }elseif($pay_order['pay_model']==2){

            $data = [

                'user_id'  => $pay_order['user_id'],

                'pay_price'=> $pay_order['pay_price'],

                'id'       => $pay_order['id'],

                'uniacid'  => $pay_order['uniacid']
            ];

            $water_model = new \app\farm\model\BalanceWater();

            $res = $water_model->addWater($data,13,1);

            if($res==0){

                return false;

            }

        }else{
            //支付宝
            $pay_model = new PayModel($payConfig);

            $res = $pay_model->aliRefund($pay_order['transaction_id'],$pay_order['pay_price']);

            if(isset($res['alipay_trade_refund_response']['code'])&&$res['alipay_trade_refund_response']['code']==10000){

                $this->dataUpdate(['id'=>$pay_order['id']],['out_refund_no'=>$res['alipay_trade_refund_response']['out_trade_no']]);

            }else{

                return ['code'=>500,'msg'=> $res['alipay_trade_refund_response']['sub_msg']];

            }

        }

        return true;
    }

    /**
     * @param $dis
     * @param int $page
     * @功能说明:后台下单列表
     * @author chenniang
     * @DataTime: 2022-02-16 14:05
     */
    public function adminDataList($dis,$page=10){

        $data = $this->alias('a')
            ->join('lbfarm_order_address b','a.id = b.order_id AND b.type=2','left')
            ->where($dis)
            ->field('a.*,b.user_name,b.mobile')
            ->group('a.id')
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;
    }

    /**
     * @param $dis
     * @param int $page
     * @功能说明:后台下单列表
     * @author chenniang
     * @DataTime: 2022-02-16 14:05
     */
    public function adminDataSelect($dis,$page=10){

        $data = $this->alias('a')
                ->join('lbfarm_order_address b','a.id = b.order_id AND b.type=2','left')
                ->where($dis)
                ->field('a.*,b.user_name,b.mobile')
                ->group('a.id')
                ->order('a.id desc')
                ->select()
                ->toArray();

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-24 16:46
     * @功能说明:预支付信息
     */
    public function payOrderInfo($input,$is_err=0){

        $claim_model = new Claim();

        $data = $claim_model->dataInfo(['id'=>$input['claim_id'],'status'=>1]);

        $input['num'] = !empty($input['num'])?$input['num']:1;

        if(empty($data)){

            return ['code'=>500,'msg'=>'该产品已下架'];
        }

        if($data['stock']<$input['num']&&$is_err==1){

            return ['code'=>500,'msg'=>'该产品库存不足'];
        }

        if($data['end_time']<time()&&$is_err==1){

            return ['code'=>500,'msg'=>'该产品认养期已结束'];

        }

        $data['pay_price'] = round($data['price']*$input['num'],2);

        $pay_price = $data['init_price'] = $data['pay_price'];

        if(!empty($input['coupon_id'])&&empty($input['collage_start_id'])){

            $coupon_record_model = new CouponRecord();

            $coupon = $coupon_record_model->dataInfo(['id'=>$input['coupon_id'],'is_claim'=>1,'status'=>1]);

            if(!empty($coupon)&&$coupon['full']<=$data['pay_price']){

                $data['pay_price'] -= $coupon['discount'];

            }else{

                $coupon = [];
            }

        }
        //发起拼团
        if(!empty($input['collage_start_id'])){

            $collage_model = new ClaimCollage();

            $data['collage_start_data'] = $collage_model->getAtvInfo($input['collage_start_id'],$input['claim_id']);

            if(!empty($data['collage_start_data'])){

                $data['pay_price'] = $data['collage_start_data']['price'];
            }
        //参与拼团
        }elseif(!empty($input['collage_join_id'])){

            $collage_model = new CollageStart();

            $data['collage_join_data'] = $collage_model->getAtvInfo($input['collage_join_id'],$input['claim_id']);

            if(!empty($data['collage_join_data'])){

                $data['pay_price'] = $data['collage_join_data']['price'];
            }

        }

        $data['pay_price'] = $data['pay_price']>0?$data['pay_price']:0;

        $data['pay_price'] = round($data['pay_price'],2);

        $data['coupon_discount'] = !empty($coupon)?$coupon['discount']:0;

        $data['coupon_discount'] = $data['coupon_discount']<$pay_price?$data['coupon_discount']:$pay_price;

        $data['coupon_discount'] = round($data['coupon_discount'],2);

        $data['coupon_id'] = !empty($coupon)?$coupon['id']:0;

        return $data;
    }









    /**
     * @author chenniang
     * @DataTime: 2022-03-09 17:45
     * @功能说明:认养发送可配送提醒
     */
    public function claimSendNotice($uniacid){

        $push_model = new PushMsgModel($uniacid);

        $dis[] = ['pay_type','>',1];

        $dis[] = ['have_notice','=',0];

        $dis[] = ['end_time','<',time()];

        $list = $this->where($dis)->select()->toArray();

        if(!empty($list)){

            foreach ($list as $value){

                $this->dataUpdate(['id'=>$value['id']],['have_notice'=>1]);

                $push_model->sendMsg($value,7);

            }

        }

        return true;
    }





}